import 'package:flutter/material.dart';

class ListTestPage extends StatefulWidget {
  @override
  _ListTestPageState createState() => _ListTestPageState();
}

class _ListTestPageState extends State<ListTestPage> {
  List<String> _data = List.generate(15, (index) => "Data: $index");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("List")),
      body: RefreshListView(
        list: _data,
        itemExtent: 50.0,
        itemBuilder: (context, index) {
          return Container(height: 100.0, child: Text(_data[index]));
        },
        refreshCallback: () async {
          await Future.delayed(Duration(seconds: 3));
        },
        loadMore: () {
          List<String> _newList = [];
          for (int i = _data.length; i < 20; i++) {
            _newList.add("Data: $i");
          }
          return Future.delayed(Duration(seconds: 2), () {
            return _newList;
          });
        },
      ),
    );
  }
}

typedef LoadMoreFuture<T> = Future<List<T>> Function();

class RefreshListView<T> extends StatefulWidget {
  final List<T> list;

  double itemExtent;

  IndexedWidgetBuilder itemBuilder;

  RefreshCallback refreshCallback;

  LoadMoreFuture loadMore;

  RefreshListView(
      {this.list,
      this.itemExtent,
      this.itemBuilder,
      this.refreshCallback,
      this.loadMore});

  @override
  _RefreshListViewState createState() => _RefreshListViewState();
}

class _RefreshListViewState extends State<RefreshListView> {
  ScrollController _controller;

  bool _isLoad = false;

  @override
  void initState() {
    super.initState();

    _controller = ScrollController()
      ..addListener(() {
        if (_controller.position.pixels ==
            _controller.position.maxScrollExtent) {
          print("到底部了");
        }
      });
  }

  Widget _buildProgressIndicator() {
    return Container(
      height: widget.itemExtent,
      child: Center(
        child: Text("正在加载..."),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      child: ListView.builder(
        itemCount: widget.list.length + 1,
        controller: _controller,
        itemBuilder: (context, index) {
          if (index == widget.list.length) {
            Widget w = _buildProgressIndicator();
            widget.loadMore().then((data) {
              setState(() {
              });
            });
            return w;
          } else {
            return widget.itemBuilder(context, index);
          }
        },
        itemExtent: widget.itemExtent,
      ),
      onRefresh: widget.refreshCallback,
    );
  }
}
